#include "stdio.h"
#include "drv_spiflash.h"
#include "soc.h"

#include "aos/hal/flash.h"

spiflash_handle_t spiFlashHandle = NULL;
spiflash_info_t *info = NULL;

typedef struct {
	spiflash_info_t spiflashinfo;
	spiflash_event_cb_t cb;
	spiflash_status_t status;
} ck_spiflash_priv_t;


void QSPI_flash_init()
{
    // int ret;
	spiFlashHandle = csi_spiflash_initialize(0, NULL);

	//16M init
    ck_spiflash_priv_t *spiflash_priv = (ck_spiflash_priv_t *)spiFlashHandle;
	spiflash_priv->spiflashinfo.end          = CSKY_QSPIMEM_BASE + 0x1000 * 0x800 *2;
    spiflash_priv->spiflashinfo.sector_count = 0x800 * 2;

	info = csi_spiflash_get_info(spiFlashHandle);
}


int32_t custom_flash_read(uint32_t offset, void *buf, uint32_t nbytes)
{
    return hal_flash_read((hal_partition_t)HAL_PARTITION_CUSTOM_1, &offset, buf, nbytes);
}

int32_t custom_flash_write(uint32_t offset, void *buf, uint32_t nbytes)
{
    return hal_flash_write((hal_partition_t)HAL_PARTITION_CUSTOM_1, &offset, buf, nbytes);
}

int32_t custom_flash_erase(uint32_t offset, uint32_t size)
{
    return hal_flash_erase((hal_partition_t)HAL_PARTITION_CUSTOM_1, offset, size);
}

//void mount_filesystem()
//{
//    FATFS fs;      /* File system object (volume work area) */
//    FIL fil;       /* File object */
//    FRESULT res;   /* API result code */
//    UINT bw;       /* Bytes written */
//    
//    res = f_mount(&fs,"0:",1);
//    
//    if (FR_NO_FILESYSTEM == res)
//    {
//        /* Create FAT volume with default cluster size */
//        char *buffer = aos_malloc(FF_MAX_SS);
//        if (buffer == NULL) {
//            return;
//        }
//        LOGI(TAG, "No filesystem. Making new filesystem...");
//        res = f_mkfs("0:", FM_FAT32, 0, buffer, FF_MAX_SS);
//        if (res != FR_OK) {
//            LOGI(TAG, "Make filesystem failed(%d)", res);
//            aos_free(buffer);
//            return;
//        }
//        aos_free(buffer);
//    
//        res = f_mount(&fs,"0:",1);
//        if (res != FR_OK)
//        {
//            LOGI(TAG, "Mount storage failed again(%d)", res);
//            return;
//        }
//    }
//    else if (res != FR_OK)
//    {
//        LOGI(TAG, "Mount storage failed(%d)", res);
//        return;
//    }
//    
//    /* Create a file as new */
//    res = f_open(&fil, "hello1.txt", FA_OPEN_ALWAYS | FA_WRITE);
//    if (res != FR_OK) {
//        LOGI(TAG, "Open file failed(%d)", res);
//        f_mount(0, "0:", 1);
//        return;
//    }
//
//    /* Write a message */
//    f_write(&fil, "Hello, World!\r\n", 15, &bw);
//    if (bw != 15)
//    {
//        LOGI(TAG, "Write file failed");
//        f_mount(0, "0:", 1);
//        return;
//    }
//    /* Close the file */
//    f_close(&fil);
//    /* Unregister work area */
//    f_mount(0, "0:", 1);
//}

